import React, { useState } from 'react';
import { message } from 'antd';
import { getEmployeeList } from '@/pages/Task/services';
import { launchTaskRate, moveToNoRate, moveToLaunch } from '../../services/score';
import ScoreModal from './index';
import { modalTypes } from './modalTypes';
import { getTaskUserConfig, saveTaskUserConfig } from '../../services';

const RatingMgtModal = ({ RatingMgtModalRef, onSuccess }) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [modalType, setModalType] = useState(null);
    const [modalData, setModalData] = useState(null);
    const [modalVisible, setModalVisible] = useState(false);
    const [userConfig, setUserConfig] = React.useState(null);
    const [employeeList, setEmployeeList] = useState([]);

    const updateOptions = async (companyId = user.companyId) => {
        const ret = [];
        const res = await getEmployeeList(companyId);
        if (res.code === 10000) {
            res.data.forEach(item => {
                // 过滤掉admin
                // if (!(item.id === 1 || item.employeeName === 'admin')) {
                ret.push({
                    label: item.employeeName,
                    value: JSON.stringify({ employeeCode: item.employeeCode, employeeName: item.employeeName })
                });
                // }
            });
        }
        setEmployeeList(ret);
    };

    const getArrayList = obj => {
        const ret = [];
        Object.values(obj).forEach(item => ret.push(...item));
        return ret;
    };

    const showWarningMessage = (msg = '请选择任务') => {
        message.warning(msg);
    };

    const getTaskUsers = async () => {
        const res = await getTaskUserConfig('score_custom_employee_list');
        const { code, data } = res;
        if (code === 10000) {
            // console.log(data);
            setUserConfig(data);
        }
    };

    const saveTaskUsers = async values => {
        if (values.taskRoleType !== '2') {
            return;
        }
        const res = await saveTaskUserConfig({
            ...userConfig,
            configType: 'score_custom_employee_list',
            configJson: JSON.stringify(values.employees.map(item => JSON.parse(item)))
        });
        const { code } = res;
        if (code === 10000) {
            getTaskUsers();
        }
    };

    const handleLaunch = (receivedDataList, mType) => {
        const dataList = Array.isArray(receivedDataList) ? receivedDataList : getArrayList(receivedDataList);
        if (dataList.length === 0) {
            return showWarningMessage();
        }
        if (dataList.length > 20) {
            return showWarningMessage('每次发起不可超过20条');
        }
        setModalType(mType);
        setModalData({ taskList: dataList });
        setModalVisible(true);
        getTaskUsers();
        return null;
    };

    const moveToNoScore = (receivedDataList, mType) => {
        const dataList = Array.isArray(receivedDataList) ? receivedDataList : getArrayList(receivedDataList);
        if (dataList.length === 0) {
            return showWarningMessage();
        }
        setModalType(mType);
        setModalData({ taskList: dataList });
        setModalVisible(true);
        return null;
    };
    const moveToBeScored = (receivedDataList, mType) => {
        const dataList = Array.isArray(receivedDataList) ? receivedDataList : getArrayList(receivedDataList);
        if (dataList.length === 0) {
            return showWarningMessage();
        }
        setModalType(mType);
        setModalData({ taskList: dataList });
        setModalVisible(true);
        return null;
    };

    const handleCommonApi = async (values, setConfirmLoading, fn, type) => {
        setConfirmLoading(true);
        const res = await fn(values);
        if (res.code === 10000) {
            message.success('提交成功');
            if (onSuccess) {
                onSuccess(type);
            }
        } else {
            message.error(res.msg || '提交失败');
        }
        setConfirmLoading(false);
        setModalVisible(false);
    };

    const handleLaunchRate = async (values, setConfirmLoading, type) => {
        const { employees, ...rest } = values;
        handleCommonApi(
            { employees: employees.map(item => JSON.parse(item)), ...rest },
            setConfirmLoading,
            launchTaskRate,
            type
        );
        saveTaskUsers(values);
    };
    const handleMoveToNoRate = async (values, setConfirmLoading, type) => {
        handleCommonApi(values, setConfirmLoading, moveToNoRate, type);
    };
    const handleMove = async (values, setConfirmLoading, type) => {
        handleCommonApi(values, setConfirmLoading, moveToLaunch, type);
    };

    const handleModalOk = (values, setConfirmLoading, type) => {
        switch (type) {
            case modalTypes.BATCH_START.key:
            case modalTypes.LAUNCH_RATE.key:
                return handleLaunchRate(values, setConfirmLoading, type);
            case modalTypes.MOVE_TO_NO_RATE.key:
            case modalTypes.BATCH_NO_SCORE.key:
                return handleMoveToNoRate(values, setConfirmLoading, type);
            case modalTypes.BATCH_MOVE.key:
            case modalTypes.MOVE_TO_WAIT.key:
                return handleMove(values, setConfirmLoading, type);
            default:
                return null;
        }
    };

    React.useImperativeHandle(RatingMgtModalRef, () => ({
        handleLaunch,
        moveToNoScore,
        moveToBeScored
    }));

    React.useEffect(() => {
        updateOptions(user.companyId);
        getTaskUsers();
    }, [user.companyId]);

    return (
        <>
            <ScoreModal
                data={modalData}
                visible={modalVisible}
                type={modalType}
                setVisible={setModalVisible}
                userConfig={userConfig}
                employeeList={employeeList}
                onOk={handleModalOk}
            />
        </>
    );
};

export default RatingMgtModal;
